using System.Reflection;
using System.Threading.Tasks;
using Newtonsoft.Json;
using StackExchange.Redis;

namespace Crossborder.Common.RedisModule
{
    public partial class RedisWorker
    {
        // public async Task<List<HashEntry>> GetHashMenory(string key)
        // {
        //     var res = await RedisCore.db.HashGetAllAsync(key);
        //     return res.ToList();
        // }

        public async Task<T> GetHashMemoryAsync<T>(string key) where T : new()
        {
            T t = new();
            var res = await RedisCore.db.HashGetAllAsync(key);
            var props = t.GetType().GetProperties();
            foreach (var item in res)
            {
                // var prop = props.Where(m => m.Name == item.Name).FirstOrDefault();
                // prop.SetValue(t, Convert.ChangeType(item.Value, prop.PropertyType));

                foreach (var prop in props)
                {
                    if (prop.Name == item.Name)
                    {
                        prop.SetValue(t, Convert.ChangeType(item.Value, prop.PropertyType));
                    }
                }
            }
            return t;
        }

        // 已废弃（使用ZSet类型作为索引代替）
        // public List<T> GetHashMemorylst<T>(string keyLike) where T : new()
        // {
        //     var keys = GetKeys(keyLike);
        //     List<T> ts = new();
        //     foreach (var key in keys)
        //     {
        //         T t = new();
        //         var res = RedisCore.db.HashGetAll(key);
        //         var props = ts.GetType().GetProperties();
        //         foreach (var item in res)
        //         {
        //             var prop = props.Where(m => m.Name == item.Name).FirstOrDefault();
        //             prop.SetValue(t, Convert.ChangeType(item.Value, prop.PropertyType));
        //         }
        //         ts.Add(t);
        //     }
        //     return ts;
        // }

        public void SetHashMemory(string key, Dictionary<string, string> values)
        {
            var hashEntrys = new List<HashEntry>();
            foreach (var value in values)
            {
                hashEntrys.Add(new HashEntry(value.Key, value.Value));
            }
            SetHashMemory(key, hashEntrys.ToArray());
        }

        public void SetHashMemory(string key, params HashEntry[] entries)
        {
            RedisCore.db.HashSet(key, entries);
            // RedisCore.db.KeyExpire(key, expire) // 设置过期时间
        }

        public void SetHashMemory<T>(string key, T entity, Type? type = null)
        {
            type ??= typeof(T);
            List<HashEntry> hashEntries = new();
            PropertyInfo[] props = type.GetProperties();
            foreach (var prop in props)
            {
                string name = prop.Name;
                object value = prop.GetValue(entity);
                // if (value is bool boolValue)
                // {
                //     var invert = boolValue ? 1 : 0;
                //     hashEntries.Add(new HashEntry(name, invert.ToString()));
                // }
                if (value.GetType().Name == "Boolean") value = (bool)value ? 1 : 0;
                {
                    hashEntries.Add(new HashEntry(name, value?.ToString()));
                }
            }
            SetHashMemory(key, hashEntries.ToArray());
        }

        public void SetHashMemory<T>(string key, IEnumerable<T> entries, Func<T, IEnumerable<string>> func)
        {
            foreach (var entity in entries)
            {
                Type type = typeof(T);
                var valuekey = func(entity);
                SetHashMemory($"{key}:{string.Join(":", valuekey)}", entity, type);
            }
        }


        /// <summary>
        /// 测试方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        // public async Task SetHashMemory<T>(string key, string cartId, T entity) where T : class
        // {
        //     var time = TimeSpan.FromSeconds(10);
        //     var json = JsonConvert.SerializeObject(entity);
        //     await RedisCore.db.HashSetAsync(key, cartId, json);
        // }

        /// <summary>
        /// 测试方法
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        // public async Task GetHashAllMemory(string key)
        // {
            // 查询所有HashValue
            // var res = await RedisCore.db.HashValuesAsync(key);

            // 查询所有 Hash值
            // var res = await RedisCore.db.HashGetAllAsync(key);
            // foreach (var e in res)
            // {
            //     var t = e.Value;
            // }

        // }
    }
}